package com.brtbeacon.wx.demo.mapview;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.webkit.JavascriptInterface;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.brtbeacon.wx.map.BRTMapWebViewPlugin;
import com.brtbeacon.wx.map.BRTMapWebViewX5Plugin;
import com.tencent.smtt.sdk.WebView;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * 智石WebView插件集成步骤演示DEMO:
 *
 * 1、如果Activity或Fragment的layout.xml资源文件中，WebView的父层容器的类型不是FrameLayout，请添加FrameLayout，并将WebView移动到里面，如下面代码：
 *
 * <FrameLayout>
 *     <WebView
 *             android:id="@+id/webView"
 *             android:layout_width="match_parent"
 *             android:layout_height="match_parent" />
 * </FrameLayout>
 *
 * 2、在Activity:onCreate()或者Fragment:onCreate()方法中，构造并初始化插件：brtWebViewPlugin = new BRTWebViewPlugin(this, webView, webViewParent);
 *
 *
 * 3、在Activity:onDestroy()方法中，调用方法：brtWebViewPlugin.onDestroy();
 *
 * 4、插件需要申请运行时权限：
 *     android.Manifest.permission.ACCESS_FINE_LOCATION
 *    android.Manifest.permission.ACCESS_COARSE_LOCATION
 *    android.Manifest.permission.CAMERA
 */

public class MapWebViewX5PluginActivity extends AppCompatActivity implements BRTMapWebViewX5Plugin.BRTWebViewPluginCallback {

    public static final  String PARAM_URL = "param_url";
    private static final int PERMISSION_REQUEST_LOCATION = 1;

    private FrameLayout webViewParent;
    private WebView webView;
    private BRTMapWebViewX5Plugin mapWebViewPlugin;

    public static void startActivity(Context ctxt, String url) {
        Intent intent = new Intent(ctxt, MapWebViewX5PluginActivity.class);
        intent.putExtra(PARAM_URL, url);
        ctxt.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view_x5_plugin);
        webView = findViewById(R.id.webView);
        //  WebView上级容器，必须为FrameLayout;
        webViewParent = findViewById(R.id.layoutFrame);
        mapWebViewPlugin = new BRTMapWebViewX5Plugin(this, webView, webViewParent);
        mapWebViewPlugin.setPluginCallback(this);
        mapWebViewPlugin.getWebView().addJavascriptInterface(ysApi, "ysApi");

        String url = getIntent().getStringExtra(PARAM_URL);
        if (TextUtils.isEmpty(url)) {
            url = "";
        }
        webView.loadUrl(url);

        needRequestPermission();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mapWebViewPlugin != null) {
            mapWebViewPlugin.onDestroy();
        }
    }

    @Override
    public void onShare(String json) {
        try {
            JSONObject jsonObject = new JSONObject(json);
            String title = jsonObject.getString("title");
            String imgUrl = jsonObject.getString("imgUrl");
            String desc = jsonObject.getString("desc");
            String link = jsonObject.getString("link");

            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.setType("text/html");
            intent.putExtra(Intent.EXTRA_SUBJECT, title);
            intent.putExtra(Intent.EXTRA_TEXT, desc + " " + link);
            startActivity(Intent.createChooser(intent, "分享到"));
        } catch (Exception e) { }
    }

    @Override
    public void onDetails(String json) {

    }

    /**
     * 设置用户数据，传入null给userId将设置成undefined;
     * @param userId
     * @param loginTime
     * 为页面全局对象 window.ysApi.userData 设置自定义数据。
     */
    private void setUserData(String userId, long loginTime) {
        String script = null;
        if (TextUtils.isEmpty(userId) || TextUtils.isEmpty(userId.trim())) {
            script = "window.ysApi.userData = undefined;";
        } else {
            //把 ysApi.userData设置成包含 userId, loginTime属性的对象
            JSONObject jsonData = new JSONObject();
            try {
                jsonData.put("userId", userId);
                jsonData.put("token", "" + loginTime);
                jsonData.put("loginTime", loginTime);
                //TODO.. 可以添加自定义属性 jsonData.put("新的属性", "属性值");
            } catch (Exception e) {}
            script = "window.ysApi.userData = " + jsonData.toString();
        }
        webView.evaluateJavascript(script, null);
    }

    //  页面全局对象 ysApi 实现
    private Object ysApi = new Object() {
        /**
         * 添加用户登录接口
         */
        @JavascriptInterface
        public void login() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    //TODO... 添加你的登录弹出对话框。当用户登录成功后，请调用setUserData()
                    Toast.makeText(MapWebViewX5PluginActivity.this, "用户登录成功!", Toast.LENGTH_SHORT).show();
                    setUserData("测试登录", Calendar.getInstance().getTimeInMillis());
                }
            });
        }

    };

    private boolean needRequestPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            String[] permissions = new String[] {
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.CAMERA
            };

            List<String> checkPermissionList = new ArrayList<>();

            for (String permission: permissions) {
                if (this.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
                    checkPermissionList.add(permission);
                }
            }

            if (!checkPermissionList.isEmpty()) {
                requestPermissions(checkPermissionList.toArray(new String[1]), PERMISSION_REQUEST_LOCATION);
                return true;
            }
        }
        return false;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case PERMISSION_REQUEST_LOCATION: {
                for (int index = 0; index < grantResults.length; ++index) {
                    if (grantResults[index] != PackageManager.PERMISSION_GRANTED) {
                        //  权限申请失败!
                        return;
                    }
                }
                //  权限申请成功!
            }
        }
    }
}
